package com.dhh.sky.activity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.json.JSONObject;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.devspark.appmsg.AppMsg;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.EditorUtil;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;

public class EditorActivity extends SherlockFragmentActivity{
	public final static int TEXT_FILE_CREATE = 1;
	public final static int TEXT_FILE_EDIT = 2;
	private EditText editor;
	private String fileName;
	private String id;
	private String path;
	private int operation = TEXT_FILE_CREATE;
	private int formatType = EditorUtil.FILEFORMAT_NL;
	private FileManager fm;
	private Context context;
	
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
        setContentView(R.layout.editor); 
        
        fm = new FileManager(this);  
        context = this;
        
        Bundle data = this.getIntent().getExtras();
        if(data!=null){
        	fileName = data.getString(Constant.PARAM_ITEM_NAME);
        	id = data.getString(Constant.PARAM_ID);
        	operation = data.getInt(Constant.PARAM_OPERATION);
        	path = data.getString(Constant.PARAM_PATH);
        }else{
        	//TODO show error info.
        }        
              
        initActionBar();
        initView();
        
        
        
        if(TEXT_FILE_EDIT==operation){
        	openFile(fileName);
        }else{
        	//TODO error handle.
        }
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem cancel = menu.add(getString(R.string.label_cancel));
		cancel.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		cancel.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {	
				EditorActivity.this.finish();
				return true;
			}
		});
		
		MenuItem save = menu.add(getString(R.string.label_ok));
		save.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		save.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(TEXT_FILE_CREATE==operation){
					showCreateDialog();
				}else{
					boolean flag = saveFile(fileName,formatType);
					if(flag){
						new SyncTextFileTask().execute(new String[]{id,path});
					}else{
						CUtil.showToast(EditorActivity.this, R.string.msg_error_save_file, AppMsg.STYLE_ALERT);
					}
					
				}

				return true;
			}
		});
		return true;
	}
	
	private void initActionBar(){
		String title = this.getString(R.string.title_new_text_file);
		if(TEXT_FILE_EDIT==operation){
			title = fileName;
			SkyDriveObject obj = fm.getFile(CUtil.getFilePreName(fileName));
			if(obj!=null){
				title = obj.getName();
			}
		}
		getSupportActionBar().setTitle(title);
        getSupportActionBar().setHomeButtonEnabled(false);    
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);  
        getSupportActionBar().setDisplayShowHomeEnabled(false);
	}
	
	private void initView(){
		editor = (EditText) this.findViewById(R.id.editor);
	}
	
	private void openFile(String fileName){
		String rawContent = EditorUtil.getFileContent(fileName);
		formatType = EditorUtil.getContentFormatType(rawContent);
		String filterContent = EditorUtil.filerContentByFormat(rawContent, formatType);
		editor.setText(filterContent);
	}
	
	private boolean createFile(String fileName){
		int formatType = EditorUtil.getContentFormatType(editor.getText().toString());
		boolean flag = saveFile(fileName,formatType);
		
		return flag;
	}
	
	public boolean saveFile(String fileName,int format){
		boolean flag = false;
		
		try {			
			File file = new File(Environment.getExternalStorageDirectory()+"/skydrive/"+fileName.toString());		
			if(!file.exists()){
				file.createNewFile();
			}
			FileWriter fstream = new FileWriter(file);
			BufferedWriter out = new BufferedWriter(fstream);

			if (format == EditorUtil.FILEFORMAT_CR){
				out.write(editor.getText().toString().replace("\n", "\r"));
			} else if (format == EditorUtil.FILEFORMAT_CRNL) {
				out.write(editor.getText().toString().replace("\n", "\r\n"));
			} else {
				out.write(editor.getText().toString());
			}
			
			out.close();
			flag = true;
		} catch (Exception e) {
			Log.e(Constant.TAG, e.getMessage(), e);
		}
		
		return flag;
	}
	
	private void showCreateDialog(){
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.dialog_create_text);
		final TextView errorText = (TextView) dialog.findViewById(R.id.txt_error);
		errorText.setTextColor(Color.RED);
		errorText.setVisibility(View.INVISIBLE);
		dialog.setTitle(context.getString(R.string.title_file_name));
		dialog.findViewById(R.id.fn_cancel).setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				dialog.dismiss();						
			}});
		dialog.findViewById(R.id.fn_add).setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				EditText nameEdit = (EditText) dialog.findViewById(R.id.txt_name);				
				String title = nameEdit.getText().toString();
				if(title==null || title.trim().length()==0){
            		errorText.setVisibility(View.VISIBLE);
            	}else{
    				fileName = title+".txt";
    				boolean flag = createFile(fileName);
    				if(flag){
    					new CreateTextFileTask().execute(new String[]{fileName,path});
    				}
            		dialog.dismiss();
            	}
			}});
		
		dialog.show();
	} 
	
	private class CreateTextFileTask extends AsyncTask<String, Void, Boolean>{
		private ProgressDialog progress;
		
		protected void onPreExecute() {
    		progress = new ProgressDialog(EditorActivity.this);
            progress.setMessage(context.getString(R.string.msg_saving_file));
            progress.show();
        }
		
		@Override
		protected Boolean doInBackground(String... params) {
			boolean flag = false;
			
			//TODO need check network is whether available			
			LiveConnectClient client = ((SDAApplication) getApplication()).getConnectClient();
			try {
				String fileName = params[0];
				String parent = params[1];
				File file = new File(Environment.getExternalStorageDirectory()+"/skydrive/"+fileName);
				LiveOperation opUpload = client.upload(parent, fileName, file);
				if(!opUpload.getResult().has(JsonKeys.ERROR)){
					SkyDriveObject obj = SkyDriveObject.create(opUpload.getResult());
					obj.setParent(parent);
					fm.addFile(obj);
					file.renameTo(new File(Environment.getExternalStorageDirectory()+"/skydrive/"+CUtil.buildFileName(obj)));
					flag = true;
				}
			}catch (Exception e) {
				Log.e(Constant.TAG, e.getMessage(), e);
			}
			return flag;
		}
		
		@Override
	    protected void onPostExecute(final Boolean success) {
			progress.dismiss();
			
			Message msg = CUtil.buildMessage();
			msg.getData().putBoolean(Constant.PARAM_DONE, true);
			resultHandler.sendMessage(msg);
		}
	}
	
	private class SyncTextFileTask extends AsyncTask<String, Void, Boolean>{
		private ProgressDialog progress;
		
		protected void onPreExecute() {
    		progress = new ProgressDialog(EditorActivity.this);
            progress.setMessage(context.getString(R.string.msg_saving_file));
            progress.show();
        }
		
		@Override
		protected Boolean doInBackground(String... params) {
			boolean flag = false;
			
			//TODO need check network is whether available			
			LiveConnectClient client = ((SDAApplication) getApplication()).getConnectClient();
			try {				
				String id = params[0];
				String parent = params[1];
				
				//rename old file.
				SkyDriveObject item = fm.getFile(id);
				String name = item.getName();
				JSONObject body = new JSONObject();
				body.put("name", CUtil.getFilePreName(name)+"_bk."+CUtil.getFileExtesion(name));
				LiveOperation opRename = client.put(id, body);
				flag = !opRename.getResult().has(JsonKeys.ERROR);
				
				//upload new file.
				if(flag){
					File file = new File(Environment.getExternalStorageDirectory()+"/skydrive/"+CUtil.buildFileName(item));
					LiveOperation opUpload = client.upload(parent, name, file);
					if(!opUpload.getResult().has(JsonKeys.ERROR)){
						flag = true;
						SkyDriveObject obj = SkyDriveObject.create(opUpload.getResult());
						obj.setParent(parent);
						fm.addFile(obj);
						file.renameTo(new File(Environment.getExternalStorageDirectory()+"/skydrive/"+CUtil.buildFileName(obj)));
					}else{
						flag = false;
						body = new JSONObject();
						body.put("name", name);
						client.post(path, body);
					}
				}
								
				//delete old file.
				if(flag){
					LiveOperation opDelete = client.delete(id);
					fm.delFile(id);
					flag = !opDelete.getResult().has(JsonKeys.ERROR);
				}
			} catch (Exception e) {
				Log.e(Constant.TAG, e.getMessage(), e);
			}
			return flag;
		}
		
		@Override
	    protected void onPostExecute(final Boolean success) {
			progress.dismiss();
			
			Message msg = CUtil.buildMessage();
			msg.getData().putBoolean(Constant.PARAM_DONE, true);
			resultHandler.sendMessage(msg);
		}
		
	}
	
	private Handler resultHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
    		boolean succ = msg.getData().getBoolean(Constant.PARAM_DONE);
    		if(succ){
    			finish();
    			Toast.makeText(EditorActivity.this, R.string.msg_save_success, Toast.LENGTH_LONG).show();
    		}else{
    			CUtil.showToast(EditorActivity.this, R.string.msg_save_error, AppMsg.STYLE_ALERT);
    		}
        }
    };  
	
}
